/*


 */

package jas.http.response;

import jas.http.request.HttpRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 *
 */
public class HttpResponseFactoryImpl implements HttpResponseFactory {
    
    private String home;
    private String serverName;
    private DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    
    public HttpResponseFactoryImpl(String home, String serverName) {
        this.home = home;
        this.serverName = serverName;
    }

    public HttpResponse createResponse(HttpRequest httpRequest) {
        HttpResponse response = null;
        
        //if (HttpRequestFormatter.isValidRequest(httpRequest)) {
            response = getResponseFromFile(home + httpRequest.getPath());
       /* } else {
            response = HttpResponse.createStandardResponse(ResponseCode.BAD_REQUEST);
        }*/
        
        response.setHeader("Server", serverName);
        response.setHeader("Content-Type", response.getContentType());
        response.setHeader("Content-Length", "" + response.getContentLength());
        
        return response;
    }

    private HttpResponse getResponseFromFile(String filename) {
        
        File file = new File(filename);
        if (file.isDirectory()) {
            filename += "index.html";
            file = new File(filename);
        }
        
        // 404 Not found
        if (!file.exists()) {
            return HttpResponse.createStandardResponse(ResponseCode.NOT_FOUND);
        }
        
        // 200 OK
        HttpResponse response = new HttpResponse();
        response.setBody(new FileResponseBody(file));
        response.setCode(ResponseCode.OK);
        response.setHeader("Date", dateFormat.format(new Date(file.lastModified())));
        
        return response;
    }
    
    
}
